package cn.xunjie.basic.service.impl;

import cn.xunjie.basic.constants.BaseConstant;
import cn.xunjie.basic.dto.LoginDto;
import cn.xunjie.basic.dto.WechatDto;
import cn.xunjie.basic.exception.BusinessException;
import cn.xunjie.basic.service.ILoginService;
import cn.xunjie.basic.util.AjaxResult;
import cn.xunjie.basic.util.HttpClientUtils;
import cn.xunjie.basic.util.MD5Utils;
import cn.xunjie.basic.util.StrUtils;
import cn.xunjie.user.domain.Logininfo;
import cn.xunjie.user.domain.User;
import cn.xunjie.user.domain.Wxuser;
import cn.xunjie.user.mapper.LogininfoMapper;
import cn.xunjie.user.mapper.UserMapper;
import cn.xunjie.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;
    @Override
    public Map<String, Object> account(LoginDto dto) {
        String username = dto.getUsername();
        Integer type = dto.getType();
        String password = dto.getPassword();
        //1.校验
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password) || StringUtils.isEmpty(type)){
            throw new BusinessException("必填哈");
        }
        //2.根据username + type 查询logininfo 要查询username phone email三个字段
        Logininfo logininfo = logininfoMapper.quryByUsernameAndType(username,type);
        //2。1 查不到...报错
        if(logininfo==null){
            throw new BusinessException("用户不存在");
        }
        //2.2查到了，校验密码是否正确
        String salt = logininfo.getSalt();
        String MD5Emp = MD5Utils.encrypByMd5(password + salt);
        if(!MD5Emp.equals(logininfo.getPassword())){
            //3.密码错误 报错
            throw new BusinessException("密码错误");
        }
        //4.登录成功
        //4.1储存redis
        UUID token = UUID.randomUUID();
        redisTemplate.opsForValue().set(
                token,
                logininfo,
                30,
                TimeUnit.MINUTES
        );
        //4。2返回token + logininfo
       Map<String, Object> map = new HashMap<>();
       logininfo.setSalt(null);
       logininfo.setPassword(null);
       map.put("token",token);
       map.put("logininfo",logininfo);
       return map;
    }

    @Override
    public AjaxResult wechat(WechatDto dto) {
        String code = dto.getCode();
        if(StringUtils.isEmpty(code)){
            throw new BusinessException("code不能为空");
        }
        String tokenUrl = BaseConstant.WeChatConstants.TOKEN_URL.replace("APPID", BaseConstant.WeChatConstants.APPID)
                .replace("SECRET", BaseConstant.WeChatConstants.SECRET)
                .replace("CODE", code);
        String tokenStr = HttpClientUtils.httpGet(tokenUrl);
        JSONObject tokenObj = JSONObject.parseObject(tokenStr);
        String accessToken = tokenObj.getString("access_token");
        String openId = tokenObj.getString("openid");
        Wxuser wxuser = wxuserMapper.loadByOpenId(openId);
        if(wxuser != null && wxuser.getUserId() != null){
            Logininfo logininfo = logininfoMapper.loadByUserId(wxuser.getUserId());
            String token = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(
                    token,
                    logininfo,
                    30,
                    TimeUnit.MINUTES
            );
            Map<String, Object> map = new HashMap<>();
            map.put("token",token);
            //我们是高级技师，应该考虑到一些敏感信息不要返回给前端
            logininfo.setSalt(null);
            logininfo.setPassword(null);
            map.put("logininfo",logininfo);
            return AjaxResult.me().setResultObj(map);
        }
        String binderParams = "?accessToken="+accessToken+"&openId="+openId;
        return AjaxResult.me().setSuccess(false).setResultObj(binderParams);
    }

    @Override
    public Map<String, Object> binder(WechatDto dto) {
        User user = userMapper.queryByphone(dto.getPhone());
        System.out.println(dto.getOpenId());
        Logininfo logininfo = null;

        if(user != null){
            logininfo = logininfoMapper.loadById(user.getLogininfoId());
        } else {
            user = dto2user(dto);
            logininfo = user2logininfo(user);
            logininfoMapper.save(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);
        }

        String wxUserUrl = BaseConstant.WeChatConstants.WXUSER_URL
               .replace("ACCESS_TOKEN",dto.getAccessToken())
               .replace("OPENID", dto.getOpenId());

        String wxUserStr = HttpClientUtils.httpGet(wxUserUrl);
        Wxuser wxuser = JSONObject.parseObject(wxUserStr, Wxuser.class);
        wxuser.setUserId(user.getId());
        wxuserMapper.save(wxuser);
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(
                token,
                logininfo,//对象要序列化
                30,
                TimeUnit.MINUTES
        );
        //4.2 返回token + logininfo
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        //我们是高级技师，应该考虑到一些敏感信息不要返回给前端
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        return map;
    }

    private Logininfo user2logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        return logininfo;
    }

    private User dto2user(WechatDto dto) {
        User user = new User();
        user.setUsername(dto.getPhone());
        user.setPhone(dto.getPhone());
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = MD5Utils.encrypByMd5(dto.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }
}
